package StudyCode.summary.BufferAndChannel;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CopyFileContentUsingSeekableByteChannel {
	public static void main(String[] args) {
		Path path = Paths.get("E:\\Copy", "1.txt");
		ByteBuffer copy = ByteBuffer.allocate(25);
		copy.put("\ntest".getBytes());
		try (SeekableByteChannel seekableByteChannel = (Files.newByteChannel(path,
				EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE)))) {
			int nbytes;
			do {
				nbytes = seekableByteChannel.read(copy);
			} while (nbytes != -1 && copy.hasRemaining());
			copy.flip();
			seekableByteChannel.position(seekableByteChannel.size());
			while (copy.hasRemaining()) {
				seekableByteChannel.write(copy);
			}
			System.out.println(copy);
			copy.clear();

		} catch (IOException ex) {
			System.err.println(ex);
		}
	}
}
